package org.dbutils.util;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @AUTHOR CJ
 * <p>
 * *@DATE 2025 - 02 - 26
 */
public class DruidUtil {
    private static DataSource dataSource;

    public static DataSource getDataSource(){
        if(dataSource == null){
            initDataSource();
        }
        return dataSource;
    }
    private static void initDataSource(){
        Properties prop = new Properties();
        try {
            prop.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception  e) {
            throw new RuntimeException(e);
        }
    }

    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        System.out.print(getConnection());
    }
    public static void close(Connection conn){
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.err.println("关闭数据库连接时发生异常");
            }
        }
    }
}
